<?php

class SiteController extends Controller {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules() {
        return array(
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('index', 'login', 'logout', 'error', 'regIDCheck', 'regUserCheck', 'register', 'regOk', 'activation', 'captcha','contact','new','newDetail','ForgotPwd','resetPwd', 'privacy', 'serice', 'fxl'),
                'users' => array('*'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('center', 'userInfo', 'changeEmail', 'changeAvatar', 'cancel', 'credit','ReSentEmail','activity','track','invite','stock','changePwd', 'order', 'orderDetail'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Declares class-based actions.
     */
    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
                'minLength' => 4, //最短为4位
                'maxLength' => 4, //是长为4位
                'testLimit'=> 1,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex() {
        $condition = new CDbCriteria();
        $condition->order='hot desc';
        $condition->addCondition('class=1');
        $rowTable = Slide::model()->findAll($condition);
        unset($condition);
        $condition = new CDbCriteria();
        $condition->order='hot desc';
        $condition->addCondition('class=3');
        $condition->limit = 3;
        $rowTable2 = Slide::model()->findAll($condition);
        unset($condition);
        $this->render('index', array(
            'rowTable' => $rowTable,
            'rowTable2' => $rowTable2,
        ));
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    //註冊時身份證驗證
    public function actionRegIDCheck() {
        $IDCard = trim($_POST['param']);
        $result = Helper::check_identity($IDCard);
        if ($result) {
            $condition = new CDbCriteria();
            $condition->addCondition("idcard='$IDCard'");
            $user = User::model()->find($condition);
            if (!$user) {
                echo 'y';
            } else {
                echo "身份證號碼已存在，請輸入其他身份證號碼";
            }
        } else {
            echo "請填真實身份證號碼，未來無法修改。贏家得標需身份證核對領取商品。";
        }
    }

    public function actionRegUserCheck($type=1) {
        $condition = new CDbCriteria();
        $param = trim($_POST['param']);
        switch ($type){
            case 1;
                $condition->addCondition("username='$param'");
                $msg = "帳號已存在，請輸入其他帳號";
                break;
            case 2:
                $condition->addCondition("email='$param'");
                $msg = "E-mail已存在，請輸入其他E-mail";
                break;
            case 3:
                $condition->addCondition("mobile='$param'");
                $msg = "手機已存在，請輸入其他手機";
                break;
            default:
                $condition->addCondition("username='$param'");
                $msg = "帳號已存在，請輸入其他帳號";
        }
        $user = User::model()->find($condition);
        if (!$user) {
            $msg = 'y';
        }
        echo $msg;
    }

    //發送郵件類SMTP
    protected function sentEmailSmtp($to, $title, $content, $att = '') {
        set_time_limit(180);
        $message = new YiiMailMessage();

        $message->setContentType("text/html");
        $message->setTo(explode(',', $to));
        $message->setFrom(array(Yii::app()->params['systemEmail'] => 'join'));
        $message->setSubject($title);
        $message->setBody($content);

        $result['result'] = true;
        try {
            Yii::app()->mail->send($message);
        } catch (Swift_ConnectionException $e) {
            $result['result'] = false;
            $result['error'] = 'There was a problem communicating with SMTP: ' . $e->getMessage();
        }
        return $result;
    }

    //獲取用戶信息
    protected function loadUser($uid) {
        return User::model()->findByPk((int) $uid);
    }

    //郵件驗證
    protected function emailVerify($uid, $email) {
        $model = $this->loadUser($uid);
        if ($model) {
            $verify = new Verify();
            $verify->type = 1;
            $verify->main = $email;
            $verify->code = rand(100000, 999999);
            $verify->status = 1;
            $verify->save();
            $url = Yii::app()->request->hostInfo . Yii::app()->createUrl('site/activation', array('uid' => $model->uid, 'code' => $verify->code, 'key' => md5($model->username)));
            $title = 'Jowin!揪贏網 會員帳號認證通知信函';            
            $content = '親愛的'.$model->realname.' ，您好：<br />
歡迎您註冊為 Jowin!揪贏網 會員，以下是您註冊的帳號資料 :<br />
帳號：'.$model->username.'<br />
電子郵件︰'.$email.'<br /><br />

在開始使用 Jowin!揪贏網 所提供的任何服務以前，您務必先完成信箱認證及手機認證程序，請點擊下方連結認證您的信箱：<br />
<a href="' . $url . '">'.$url.'</a><br />
如果您無法按下認證連結，請直接複製網址貼到瀏覽器網址列。<br /><br />

如果您不曾於 Jowin!揪贏網 建立帳號，請點擊以下鏈結告訴我們:<br />
<a href="http://www.jowinwin.com">http://www.jowinwin.com</a><br /><br />

※貼心提醒 :<br />
1.	如果認證信重複寄送，請以最後一封認證信啟動，會員資料將以最終啟動會員帳號的Email 為準!<br />
2.	此為系統自動通知信，請勿直接回信！如您有需要其他服務的地方，請與「客服中心」聯絡，我們將竭誠為您服務！<br />
3.	請妥善保存並維護密碼隱私性以保障您的權益。<br />
4.	Jowin!揪贏網 不會主動以任何形式要求會員提供密碼。<br /><br />
Jowin!揪贏網團隊 敬上<br /><br />

____________________________________________________________________________________________<br />
Jowin!揪贏網 <br />
http://www.jowinwin.com

Jowin!揪贏網 Facebook粉絲團連結<br />
https://www.facebook.com/pages/Join-To-Win-%E6%8F%AA%E8%B4%8F%E7%B6%B2/137786092972951<br /><br />

客服中心連結 : www.jowinwin.com/service
';
            return $this->sentEmailSmtp($email, $title, $content);
        } else {
            return array('result' => false);
        }
    }

    //重送郵件驗證信
    public function actionReSentEmail() {
        $uid = (int) $_POST['uid'];
        $email = trim($_POST['email']);
        if (Helper::check_email($email)) {
            $condition = new CDbCriteria();
            $condition->addCondition("email='".$email."'");
//            $condition->addCondition('email_status=1');
            $result2 = User::model()->find($condition);
//            echo CJSON::encode(array('success' => true, 'msg' => $result2));exit;
            if(!$result2){
               $result = $this->emailVerify($uid, $email);
            
                if ($result['result']) {
                    $msg = '郵件發送成功，請查收！';
                } else {
                    $msg = '郵件發送失敗！';
                } 
            }else{
                $msg = 'Email已經被其他人使用，請輸入其他Email！';
            }            
            
        } else {
            $msg = 'Email位置不正确！';
        }
        echo CJSON::encode(array('success' => true, 'msg' => $msg));
    }

    /**
     * Displays the contact page
     */
    public function actionContact() {
        $model = new Contact;
        if (Yii::app()->request->isPostRequest) {
            $model->class = $_POST['class'];
            $model->name = $_POST['name'];
            $model->lastname = $_POST['lastname'];
            $model->phone = $_POST['phone'];
            $model->age = $_POST['age'];
            $model->email = $_POST['email'];
            $model->title = $_POST['title'];
            $model->message = $_POST['message'];
            if($model->save()){
                header("Content-type:text/html;charset=utf-8");
                echo '<script>alert("提交成功！");window.location.href="' . Yii::app()->createUrl('site/contact') . '"</script>';
            }
        }
        $this->render('contact',array(
                'model'=>$model,
            )
        );
    }

    //Register
    public function actionRegister() {
        if($_REQUEST['invite']){
            $inviteUser = User::model()->findByPk((int)$_REQUEST['invite']);
            if($inviteUser){
                Yii::app()->session->add('invite_user', $inviteUser->uid);
            }
        }        
        if (Yii::app()->request->isPostRequest) {
            //判斷用戶是否已經存在
            $user = User::model()->find("username='".trim($_POST['username'])."'");
            if(!$user){
                if (trim($_POST['password']) == trim($_POST['repassword'])) {
                    $model = new User;
                    $model->realname = trim($_POST['realname']);
                    $model->username = trim($_POST['username']);
                    $model->password = md5(trim($_POST['password']));
                    $model->email = trim($_POST['email']);
                    $model->address = trim($_POST['address']);
                    $model->birthday = trim($_POST['birthday']);
                    $model->mobile = trim($_POST['mobile']);
                    $model->idcard = trim($_POST['idcard']);                    
                    if ($model->save()) {                        
                        if(Yii::app()->session->get('invite_user')){
                            //增加coinitem記錄
                            $item = new CoinItem();
                            $item->uid = $model->uid;
                            $item->amount = Yii::app()->params['invitehongyun'];
                            $item->type = 2;
                            $item->source = 2;
                            $item->status = 1;
                            $item->effectdate = date('Y-m-d');
                            $item->save();
                            unset($item);
                        }
                        if (Yii::app()->params['emailVerify']) {
                            $verifyResult = $this->emailVerify($model->uid, $model->email);
                            if ($verifyResult['result']) {
                                $msg = "註冊成功，帳戶啟動郵件已經發送到你的註冊信箱，請查收！";
                            } else {
                                $msg = "註冊成功，帳戶啟動郵件發送失敗，請登錄后重新發送帳戶啟動郵件，或者更換郵箱！";
                            }
                        } else {
                            $msg = "註冊成功！";
                        }
                        Yii::app()->session->add('temp_uid', $model->uid);
                        Yii::app()->session->add('reg_msg', $msg);
                        $this->redirect($this->createUrl('RegOk'));
                    }
                }
            }else{
                //header("Content-type:text/html;charset=utf-8");
                //echo '<script>alert("帳號已存在，請輸入其他帳號");</script>';
            }
        }
        $this->render('register', array('model' => $model));
    }

    //註冊成功頁
    public function actionRegOk() {
        $uid = (int) Yii::app()->session->get('temp_uid');
        $msg = Yii::app()->session->get('reg_msg');
        Yii::app()->session->add('temp_uid', '');
        Yii::app()->session->add('reg_msg', '');
        $user = $this->loadUser($uid);
        if (!$user) {
            $this->redirect($this->createUrl('index'));
        }
        $this->render('regok', array('model' => $model, 'msg' => $msg));
    }

    //用戶激活
    public function actionActivation() {
        $uid = (int) $_GET['uid'];
        $key = trim($_GET['key']);
        $code = trim($_GET['code']);
        $user = $this->loadUser($uid);
        $criteria = new CDbCriteria;
        $criteria->addCondition("status=1");
        $criteria->addCondition("type=1");
        $criteria->addCondition("code=" . $code);
        $verify = Verify::model()->find($criteria);
        unset($criteria);
        header("Content-type:text/html;charset=utf-8");
        if ($verify && $key = md5($user->username)) {
            $verify->status = 2;
            $verify->save();
            $user->email = $verify->main;
            $user->email_status = 1;
            $user->save();
            echo '<script>alert("驗證成功，請登錄。");window.location.href="' . Yii::app()->createUrl('site/login') . '"</script>';
        } else {
            echo '<script>alert("非法的驗證鏈接。");window.location.href="' . Yii::app()->createUrl('site/index') . '"</script>';
        }
    }

    //用戶登錄
    public function actionLogin() {
        //返回地址
        $returnUrl = $_REQUEST['return'];
        if($returnUrl){
            Yii::app()->user->returnUrl = base64_decode($returnUrl);
        }
        
        $model = new LoginForm;

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (Yii::app()->request->isPostRequest) {
            $model->username = trim($_POST['username']);
            $model->password = trim($_POST['password']);
            if ($this->createAction('captcha')->getVerifyCode() == trim($_POST['verifycode'])) {
                if ($model->validate() && $model->login()) {
                    $this->redirect(Yii::app()->user->returnUrl);
//                    $this->redirect(array('center'));
                } else {
                    $msg = "用戶名或密碼錯誤！";
                }
            } else {
                $msg = "驗證碼錯誤！";
            }
        }
        // display the login form
        $this->render('login', array('model' => $model, 'msg' => $msg));
    }

    //登出
    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(array('index'));
    }

    //會員中心
    public function actionCenter() {
        $model = $this->loadUser(Yii::app()->user->id);
        Helper::coinComeTrue($model->uid);
        $this->render('center', array('model' => $model));
    }

    //會員中心
    public function actionUserInfo() {
        $model = $this->loadUser(Yii::app()->user->id);
        if (Yii::app()->request->isPostRequest) {
            $model->nickname = trim($_POST['nickname']);
            $model->sex = trim($_POST['sex']);
            $model->blood = trim($_POST['blood']);
            $model->address = trim($_POST['address']);
            $model->birthday = trim($_POST['birthday']);
            $model->mobile = trim($_POST['mobile']);
            $model->postcode = trim($_POST['postcode']);
            $model->occupation = trim($_POST['occupation']);
            $model->salary = trim($_POST['salary']);
            $model->education = trim($_POST['education']);
            $model->marital = trim($_POST['marital']);
            if ($model->save()) {
                $success = '更新成功';
            }
        }
        $this->render('userinfo', array('model' => $model, 'success' => $success));
    }

    //更換郵箱
    public function actionChangeEmail() {
        $this->layout = 'pop';
        $model = $this->loadUser(Yii::app()->user->id);
        $this->render('changeemail', array('model' => $model));
    }

    //更換頭像
    public function actionChangeAvatar() {
        $model = $this->loadUser(Yii::app()->user->id);
        $this->layout = 'pop';
        if (Yii::app()->request->isPostRequest) {
            $image = CUploadedFile::getInstanceByName('fileField');
            $hg = explode('.', $image->name);
            $hgc = count($hg) - 1;
            $hg = $hg[$hgc];
            $filename = time() . rand(100, 999) . '.' . $hg;
            $name = Yii::app()->params['avatarPath'] . '/' . $filename;
            if ($image && $image->saveAs($name)) {
                $model->avatar = $filename;
                if ($model->save()) {
                    $msg = '更新頭像成功！';
                } else {
                    $msg = '更新頭像失敗！';
                }
            } else {
                $msg = '更新頭像失敗！';
            }
        }
        $this->render('avatar', array('model' => $model, 'msg' => $msg));
    }

    //訂單中心
    public function actionOrder() {
        $condition = new CDbCriteria();
        $condition->addCondition('uid=' . Yii::app()->user->id);
        //查詢條件
        if (Yii::app()->request->isPostRequest) {
            $search['status'] = $_POST['status'];
            $search['oid'] = $_POST['oid'];
            if ($search['status']) {
                $condition->addCondition('status=' . (int) $search['status']);
            }
            if ($search['oid']) {
                $condition->addCondition('oid=' . (int) $search['oid']);
            }
        }

        $count = Order::model()->count($condition);
        $pager = new CPagination($count);
        $pager->pageSize = 8;
        $pager->applyLimit($condition);
        $rowset = Order::model()->findAll($condition);
        $this->render('order', array(
            'rowset' => $rowset,
            'search' => $search,
            'pages' => $pager,
        ));
    }

    //訂單詳細
    public function actionOrderDetail($oid) {
        $order = Order::model()->findByPk((int) $oid);
        $this->render('orderdetail', array('row' => $order));
    }

    //取消訂單
    public function actionCancel() {
        $oid = (int) $_POST['oid'];
        $condition = new CDbCriteria();
        $condition->addCondition('uid=' . Yii::app()->user->id);
        $condition->addCondition('oid=' . $oid);
        $order = Order::model()->find($condition);
        unset($condition);
        if ($order->status == 1) {
            $order->status = 5;
            $user = User::model()->findByPk($order->uid);
            $trans = Yii::app()->db->beginTransaction();
            try {
                //訂單主記錄保存
                $order->save();

                if($order->coin>0){
                    //從用戶購物金餘額中返還金幣
                    $user->coin = $user->coin + $order->coin;
                    $user->save();

                    //保存coin flow記錄
                    $record = new CoinFlow();
                    $record->uid = $user->uid;
                    $record->type = 1;
                    $record->amount = $order->coin;
                    $record->flow_type = 1;
                    $record->description = '訂單（' . $order->oid . '）取消，返還購物金。';
                    $record->save();
                }                

                //已付款的訂單，增加返點和返購物金記錄
                Helper::cancelCoinByOrder($order->oid);
                
                //提交
                $trans->commit();
                $msg = '訂單取消成功';
                Helper::cancelOrderEmail($order->oid);
            } catch (Exception $e) {
                $trans->rollback();
//            echo $e->getMessage();
//            $this->response(array('status' => 1, 'msg' => $e->getMessage()));
                $msg = '訂單取消失敗';
            }
            echo CJSON::encode(array('success' => true, 'msg' => $msg));
        }
    }

    //購物金明細
    public function actionCredit() {
        $model = $this->loadUser(Yii::app()->user->id);
        $condition = new CDbCriteria();
        $condition->addCondition('uid=' . $model->uid);
        
        $count = CoinItem::model()->count($condition);
        $pager = new CPagination($count);
        $pager->pageSize = 10;
        $pager->applyLimit($condition);
        $rowset = CoinItem::model()->findAll($condition);
        unset($condition);
        $this->render('credit', array(
            'rowset' => $rowset,
            'model' => $model,
            'pages' => $pager,
        ));
    }
    
    //參與活動記錄
    public function actionActivity(){
        $condition = new CDbCriteria();
        $condition->select = 'activityid';
        $condition->addCondition('uid='.Yii::app()->user->id);
        $condition->group = 'activityid';
        $activitys = Record::model()->findAll($condition);
        unset($condition);
        $activityidArr = array();
        
        if($activitys){
            foreach($activitys as $activity){
                $activityidArr[] = $activity['activityid'];
            }
        }
        
        $condition = new CDbCriteria();
        $condition->with = 'prize';
        $condition->with = 'records';
        $condition->addInCondition('t.activityid', $activityidArr);
        $count = Activity::model()->count($condition);
        $condition->order = 't.hot desc,t.dateline desc';
        $pager = new CPagination($count);
        $pager->pageSize = 3;
        $pager->applyLimit($condition);
        $rowTable = Activity::model()->findAll($condition);
        unset($condition);
        $this->render('activity', array(
            'rowTable' => $rowTable,
            'pages' => $pager,
        ));
    }
    
    //追蹤中的活動
    public function actionTrack(){
        $condition = new CDbCriteria();
        $condition->with = 'user';
        $condition->with = 'activity';
        $condition->addCondition('uid='.Yii::app()->user->id);
        $count = Track::model()->count($condition);
        $condition->order = 't.dateline desc';
        $pager = new CPagination($count);
        $pager->pageSize = 3;
        $pager->applyLimit($condition);
        $rowTable = Track::model()->findAll($condition);
        unset($condition);
        $this->render('track', array(
            'rowTable' => $rowTable,
            'pages' => $pager,
        ));
    }
    
    //推薦好友
    public function actionInvite(){
        if (Yii::app()->request->isPostRequest) {
            $title = trim($_POST['title']);
            $name = trim($_POST['name']);
            $email = trim($_POST['email']);
            $message = trim($_POST['message']);
            
            $msg = '';
            if(!$title){
                $msg .= '主旨不能為空'."\\n\\n";
            }
            
            if(!$name){
                $msg .= '你的姓名/暱稱不能為空'."\\n\\n";
            }
            
            if(!Helper::check_email($email)){
                $msg .= 'Email格式錯誤'."\\n\\n";
            }
            
            if(!$message){
                $msg .= '留言不能為空'."\\n\\n";
            }
            $user = User::model()->findByPk(Yii::app()->user->id);
            if(!$msg){                
                $title = '您的好友 '.$user->realname.' 推薦您加入 Jowin揪贏網 同樂!';
                $content = '您好! 您的好友 (會員姓名) 推薦您加入 Jowin!揪贏網 同樂!<br /><br />
Jowin!揪贏網 為一抽獎活動平台，不定時會舉辦多項好康抽獎活動，新的好康活動將公告於Jowin!揪贏網 Facebook粉絲團公告欄，只要您透過以下推薦連結完成會員註冊及身分驗證程序，除了可免費獲得 Jowin!揪贏網 回饋的<font stlye="color:red;">'.Yii::app()->params['invitehongyun'].'點鴻運點數</font>外，還可即刻參加好康抽獎活動，並有機會獨得各項大獎!<br /><br />
請使用下列連結完成推薦程序，如果您無法按下認證連結，請直接複製網址貼到瀏覽器網址列。<br />
'.Yii::app()->request->hostInfo . Yii::app()->createUrl('site/register', array('invite' => $user->uid)).'<br /><br />

※貼心提醒 : <br />
此為系統自動通知信，請勿直接回信！如您有需要其他服務的地方，請與「客服中心」聯絡，我們將竭誠為您服務！<br /><br />
Jowin!揪贏網團隊 敬上<br /><br />

____________________________________________________________________________________________<br />
Jowin!揪贏網 <br />
http://www.jowinwin.com

Jowin!揪贏網 Facebook粉絲團連結<br />
https://www.facebook.com/pages/Join-To-Win-%E6%8F%AA%E8%B4%8F%E7%B6%B2/137786092972951<br /><br />

客服中心連結 : www.jowinwin.com/service
';
                
                $result = $this->sentEmailSmtp($email, $title, $content);
                if($result['result']){
                    $msg = '郵件發送成功';
                }else{
                    $msg = '郵件發送失敗';
                }
            }

        }
        $this->render('invite', array('msg' => $msg));
    }
    
    //消息列表
    public function actionNew(){        
        $condition = new CDbCriteria();        
        $count = News::model()->count($condition);
        $condition->order = 't.hot desc';
        $pager = new CPagination($count);
        $pager->pageSize = 20;
        $pager->applyLimit($condition);
        $rowTable = News::model()->findAll($condition);
        unset($condition);
        $this->render('new', array(
            'rowTable' => $rowTable,
            'pages' => $pager,
        ));
    }
    
    //消息詳情
    public function actionNewDetail($id){
        $row = News::model()->findByPk((int)$id);
        $this->render('newdetail', array(
            'row' => $row,
        ));
    }
    
    //儲物區
    public function actionStock(){
        $condition = new CDbCriteria();
        $condition->addCondition('status=4');
        $condition->addCondition('uid='.Yii::app()->user->id);
        $orders = Order::model()->findAll($condition);
        unset($condition);
        
        $oidArr = array();
        
        foreach($orders as $order){
            $oidArr[] = $order->oid;
        }
        
        $condition = new CDbCriteria();
        $condition->addInCondition('oid', $oidArr);
        $condition->with = 'product';
        $condition->addCondition("product.type='虛擬'");
        $rowTable = OrderItem::model()->findAll($condition);
        unset($condition);
        
        $rowSet = array_chunk($rowTable, 5);
       
        $this->render('stock', array(
            'rowSet' => $rowSet,
        ));
    }
    
    //修改密碼
    public function actionChangePwd(){
        $this->layout = 'pop';
        $model = $this->loadUser(Yii::app()->user->id);
        if (Yii::app()->request->isPostRequest) {
            if(md5($_POST['oldpwd'])==$model->password){
                if($_POST['newpwd']==$_POST['renewpwd']){
                    $model->password = md5($_POST['newpwd']);
                    if($model->save()){
                        $msg = '密碼更新成功';
                    }else{
                        $msg = '密碼更新失敗';
                    }
                }else{
                    $msg = '兩次輸入的新密碼不一致';
                }
            }else{
                $msg = '舊密碼錯誤';
            }            
        }
        $this->render('changepwd', array('msg' => $msg));
    }
    
    //忘記密碼
    public function actionForgotPwd(){
        $this->layout = 'pop';
        if (Yii::app()->request->isPostRequest) {
            $email = $_POST['email'];
            if (Helper::check_email($email)) {
                $condition = new CDbCriteria();
                $condition->addCondition("email='".$email."'");
                $result2 = User::model()->find($condition);
                if($result2){
                    $tempPwd = rand(100000,999999);
                    $string = Helper::authcode($tempPwd.'||'.$result2['uid'], 'ENCODE', '', 3600);
                    $title = 'Jowin!揪贏網 會員密碼變更通知信函';
                    $content = '親愛的 '.$result2['realname'].' ，您好：<br />
您在 Jowin!揪贏網 的帳號為：'.$result2['username'].'<br />
您申請設定的新密碼為：'.$tempPwd.'<br /><br />
請使用下列連結啟用新密碼，如果您無法按下認證連結，請直接複製網址貼到瀏覽器網址列。 <br />
'.Yii::app()->request->hostInfo . Yii::app()->createUrl('site/resetPwd', array('code' => $string)).'<br /><br />
※貼心提醒 : 
1.	請妥善保存並維護密碼隱私性，登入後請立刻更換成新密碼。<br />
2.	此為系統自動通知信，請勿直接回信！如您有需要其他服務的地方，請與「客服中心」聯絡，我們將竭誠為您服務！<br /><br />

Jowin!揪贏網團隊 敬上<br /><br />

____________________________________________________________________________________________<br />
Jowin!揪贏網 <br />
http://www.jowinwin.com<br /><br />

Jowin!揪贏網 Facebook粉絲團連結<br />
https://www.facebook.com/pages/Join-To-Win-%E6%8F%AA%E8%B4%8F%E7%B6%B2/137786092972951<br /><br />

客服中心連結 : www.jowinwin.com/service';
                    Helper::sentEmailSmtp($email, $title, $content);
                    $msg = "郵件發送成功，請查收";
                }else{
                    $msg = "無此用戶";
                }
            }else{
                $msg = '郵箱地址輸入錯誤，請檢查';
            }
        }
        $this->render('forgotpwd', array('msg' => $msg));
    }
    
    //找回密碼
    public function actionResetPwd(){
        $code = $_GET['code'];
        $string = Helper::authcode($code, 'DECODE');
        if($string){
            $codeArr = explode('||',$string);
            $uid = $codeArr[1];
            $pwd = $codeArr[0];
//            var_dump($codeArr);exit;
            $user = User::model()->findbypk((int)$uid);
            if($user && $pwd){
                $user->password = md5($pwd);
                if($user->save()){
                    $msg = '密碼重置成功，請登錄后及時修改';
                }else{
                    $msg = '密碼重置失敗';
                }
            }else{
                $msg = '密碼重置失敗';
            }
        }else{
            $msg = '鏈接已失效';
        }
        header("Content-type: text/html; charset=utf-8");
        echo '<script>alert("'.$msg.'");window.location.href="index.php";</script>';
    }
    
    //服務條款
    public function actionPrivacy(){
        $this->render('privacy');
    }
    //服務條款
    public function actionSerice(){
        $this->render('serice');
    }
    
    //測試
    public function actionFxl() {
//        $model = User::model()->findByPk(1);
//        $title = '註冊驗證信件';
//        $content = '註冊驗證信件內容：<a href="' . Yii::app()->request->hostInfo . Yii::app()->createUrl('site/activation', array('uid' => $model->uid, 'key' => md5($model->username . $model->password))) . '">啟動帳戶鏈接</a>';
//        $result = $this->sentEmailSmtp($model->email, $title, $content);
//        var_dump($result);
//        echo $model->realname;
//        $model->username = '111';
//        $model->validate();
//        $msg = CHtml::errorSummary($model, '請檢查以下錯誤：');
//        echo $msg;
//        echo date('Y-m-d',strtotime('+30 day'));
//        Helper::getunEffectCoin(2, 1);
//        echo date('Y-m-d',  strtotime('+1 year'));
//        Helper::coinComeTrue();
//        echo Helper::authcode(111111, 'ENCODE', '', 20);
//        echo Helper::authcode($_GET['code'], 'DECODE');
    }

}